//
//  LCChiDaoController.swift
//  mggz
//
//  Created by Apple on 2018/4/24.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD
import RxSwift
import RxCocoa

class LCChiDaoController: UIViewController {

    @IBOutlet var timelabel: UILabel!
    @IBOutlet var totalistView: UITableView!
    @IBOutlet var detailistView: UITableView!
    @IBOutlet weak var line: UIView!
    @IBOutlet weak var projectName: UILabel!
    @IBOutlet weak var tellayout: UIView!
    var tellabel: UILabel?
    var telImg:UIImageView?
    var emptyview:EmptyView?
    
    var phonenumber:String? = ""
    
    var datavariable:PublishSubject<[DWItem]> = PublishSubject()
    var datatotal:[DWItem] = [DWItem]()
    
    var detailvariable:PublishSubject<[ChiDaoItemResult]> = PublishSubject()
    
    var workIdvariable:PublishSubject<String> = PublishSubject()
    
    var month:String?
    var number:Int?
    var monthStr:String?
    
    
    lazy var gradientLayer:CAGradientLayer = {
        var layer = CAGradientLayer()
        layer.colors = [UIColor.LightBeautifutGreen80.cgColor,UIColor.LightBeautifutGreen.cgColor]
        layer.locations = [0.4,1]
        layer.startPoint = CGPoint(x: 0, y: 0)
        layer.endPoint = CGPoint(x:0,y:1)
        return layer
    }()
    
    lazy var callTap:UITapGestureRecognizer = {
        var tap = UITapGestureRecognizer(target: self, action: #selector(call(_:)))
        tap.numberOfTapsRequired = 1
        tap.numberOfTouchesRequired = 1
        return tap
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let img = UIColor.LightGreyBG.createImageWithColor()
        self.navigationController?.navigationBar.setBackgroundImage(img, for: .default)
        self.navigationController?.navigationBar.shadowImage = img
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.setBackgroundImage(UIColor.white.createImageWithColor(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIColor.gray.withAlphaComponent(0.5).createImageWithColor()
        
        self.workIdvariable.dispose()
        self.detailvariable.dispose()
        self.datavariable.dispose()
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tellabel = UILabel()
        self.tellabel?.textColor = UIColor.white
        self.tellabel?.text = ""
        self.tellabel?.font = UIFont.systemFont(ofSize: 20.0)
        
        self.telImg = UIImageView()
        self.telImg?.image = UIImage(named: "联系")
        self.telImg?.contentMode = .scaleAspectFill
        
        self.navigationItem.title = "迟到/早退"
        self.projectName.text = ProjectName as! String
        
        self.tellayout.backgroundColor = UIColor.clear
        self.tellayout.isUserInteractionEnabled = true
        self.tellayout.addGestureRecognizer(self.callTap)
        
        self.totalistView.backgroundColor = UIColor.LightGrey
        self.timelabel.text = self.monthStr
        self.totalistView.register(UINib(nibName: "UserItem", bundle: nil), forCellReuseIdentifier: "cell")
        self.totalistView.tableFooterView = UIView(frame: CGRect.zero)
        self.totalistView.separatorStyle = .none//CDListItem
        self.totalistView.bounces = false
        
        self.detailistView.register(UINib(nibName: "CDListItem", bundle: nil), forCellReuseIdentifier: "CDListItem")
        self.detailistView.tableFooterView = UIView(frame: CGRect.zero)
        self.detailistView.separatorStyle = .singleLine
        self.detailistView.bounces = false
        
        self.datavariable.asObservable().bind(to: self.totalistView.rx.items){
            (_,row,element) in
            let cell = self.totalistView.dequeueReusableCell(withIdentifier: "cell", for: IndexPath(row : row, section : 0)) as! UserItem
            cell.chidaoItem = element
            return cell
        }
        
        self.totalistView.rx.modelSelected(DWItem.self).subscribe { (event) in
            print("\(event.element?.DemandBaseMigrantWorkerID!)")
            self.getDetailList((event.element?.DemandBaseMigrantWorkerID)!)
            self.tellabel?.text = event.element?.LealPersonPhone ?? ""
            self.phonenumber = event.element?.LealPersonPhone ?? ""
        }
        
        self.detailvariable.asObservable().bind(to: self.detailistView.rx.items){
            (_,row,element) in
            let cell = self.detailistView.dequeueReusableCell(withIdentifier: "CDListItem", for: IndexPath(row : row, section : 0)) as! CDListItem
            cell.dataitem = element
            cell.selectionStyle = .none
            return cell
        }
        
        self.workIdvariable.subscribe(onNext: { (data) in
            print("\(data)")
            SVProgressHUD.show(withStatus: "正在加载")
            self.getDetailList(data)
        })
        
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)
        
        if self.number == 0{
            self.addEmptyView("当月没有迟到数据")
        }else{
            self.getTotalList()
        }
        //self.gradientLayer.frame = self.tellayout.layer.bounds
        print("\(self.tellayout.layer.bounds)")
        self.tellayout.layer.addSublayer(self.gradientLayer)
        
        self.tellayout.addSubview(self.tellabel!)
        self.tellayout.addSubview(self.telImg!)
        
        self.telImg?.snp.updateConstraints({ (make) in
            make.centerY.equalTo(self.tellayout)
            make.left.equalTo(self.tellayout.snp.left).offset(ScreenWidth/8)
            make.size.equalTo(CGSize(width: 28, height: 28))
        })
        
        self.tellabel?.snp.updateConstraints({ (make) in
            make.centerY.equalTo(self.tellayout)
            //make.centerX.equalTo(self.tellayout)
            make.left.equalTo((self.telImg?.snp.right)!).offset(5)
        })
        
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.gradientLayer.frame = self.tellayout.layer.bounds
    }
    
    func getTotalList(){
        SVProgressHUD.show(withStatus: "正在加载中")
        var params:[String:Any] = ["month":self.month!,"constructionProjectID":ProjectId as! String]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .ChiDaoTotal, params: &params, type: DWTotal.self, success: { (bean,_) in
            guard let data = bean as? DWTotal else{
                return
            }
            self.datavariable.onNext(data.Result!)
            guard (data.Result?.count)! > 0 else{
                print("没有数据")
                return
            }
            self.tellabel?.text = data.Result?.first?.LealPersonPhone ?? ""
            self.phonenumber = data.Result?.first?.LealPersonPhone ?? ""
            self.workIdvariable.onNext((data.Result?.first?.DemandBaseMigrantWorkerID)!)
            self.totalistView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .top)
        }) { (error) in
            switch error{
            case .DATAERROR:
                self.addEmptyView("数据异常")
                break;
            case .DATAFAIL:
                break;
            case .HTTPERROR:
                self.addEmptyView("网络异常")
                break;
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("数据异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
            SVProgressHUD.dismiss()
        }
    }
    
    
    func getDetailList(_ workid:String){
        var params:[String:Any] = ["month":self.month!,"demandBaseMigrantWorkerID":workid,"constructionProjectID":ProjectId as! String]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .ChiDaoDetail, params: &params, type: ChiDaoItem.self, success: { (bean,_) in
            guard let data = bean as? ChiDaoItem else{
                print("空数据")
                return
            }
            self.detailvariable.onNext(data.Result!)
            SVProgressHUD.dismiss()
        }) { (error) in
            switch error{
            case .DATAERROR:
                self.addEmptyView("数据异常")
                break;
            case .DATAFAIL:
                break;
            case .HTTPERROR:
                self.addEmptyView("网络异常")
                break;
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("数据异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
            SVProgressHUD.dismiss()
        }
    }
    
    func addEmptyView(_ status:String = "网络异常"){
        if self.emptyview != nil{
            self.emptyview?.removeFromSuperview()
            self.emptyview = nil
        }
        self.emptyview = EmptyView(frame: CGRect.zero, _title: status, _top: Float(ScreenHeight/5))
        self.view.addSubview(self.emptyview!)
        self.emptyview?.snp.updateConstraints({ (make) in
            make.top.equalTo(self.line.snp.bottom)
            make.left.equalTo(self.view.snp.left)
            make.right.equalTo(self.view.snp.right)
            make.bottom.equalTo(self.view.snp.bottom)
        })
    }
    
    @objc func call(_ sender:UIGestureRecognizer){
        if !((self.phonenumber?.isEmpty)!){
            UIApplication.shared.openURL(URL(string: "telprompt:\(self.phonenumber ?? "")")!)
        }
        
    }
    
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
